package practise.trackerpoc.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import practise.trackerpoc.shared.CenterProp;
import practise.trackerpoc.shared.MemberProp;

import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Load;

@Entity
@Cache
public class Member {
	@Id Long id;
	
	@Index String nameFirst;
	String nameMiddle;
	@Index String nameLast;
	
	@Index String email1;
	@Index String email2;
	
	Phone phoneHome;
	Phone phoneOffice;
	Phone phoneMobile;
	Phone phoneAlternate;
		
	String addressHome;
	String addressOffice;
	
	Date dob;
	
	@Load @Index private List<Ref<Center>> centers;
	
	void addCenter(Center center) {
		if (null == centers)
			centers = new ArrayList<Ref<Center>>();
			
		centers.add(Ref.create(center));
	}
	
	ArrayList<CenterProp> getCenters() {
		ArrayList<CenterProp> list = new ArrayList<CenterProp>();
		
		if (null != centers) {
			for (Ref<Center> centerRef : centers) {
				list.add(centerRef.get().toCenterProp());
			}
		}
		
		return list;
	}
	
	public Member() {
		// TODO Auto-generated constructor stub
	}
				
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("id = " + id + ", name = " + nameFirst + " " + nameMiddle + 
				" " + nameLast + ", email(s) = " + email1 + ", " + email2 +
				", phone(s) = " + phoneHome + ", " + phoneOffice + ", " + phoneMobile + " " + 
				", houseAddress = " + addressHome +
				" centers = [");
		
		for (CenterProp c : getCenters()) {
			sb.append(c + ", ");
		}
		sb.append("]");
		
		return sb.toString();
	}
	
	public MemberProp toMemberProp() {
		MemberProp prop = new MemberProp();
		prop.id = id;
		
		prop.nameFirst = nameFirst;
		prop.nameMiddle = nameMiddle;
		prop.nameLast = nameLast;
		
		prop.email1 = email1;
		prop.email2 = email2;
		
		if (null != phoneHome) prop.phoneHome = phoneHome.toPhoneProp();
		if (null != phoneOffice) prop.phoneOffice = phoneOffice.toPhoneProp();
		if (null != phoneMobile) prop.phoneMobile = phoneMobile.toPhoneProp();
		if (null != phoneAlternate) prop.phoneAlternate = phoneAlternate.toPhoneProp();
		
		prop.addressHome = addressHome;
		prop.addressOffice = addressOffice;
		
		prop.dob = dob;
		
		if (null != centers) {
			prop.centers = getCenters();
		}
			
		
		return prop;		
	}
}
